package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.AuthService;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class AuthController {
    private final AuthService authService;

    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> credentials) {
        String username = credentials.get("username");
        String password = credentials.get("password");

        Map<String, Object> response = new HashMap<>();

        try {
            boolean authenticated = authService.authenticate(username, password);
            if (authenticated) {
                response.put("status", "success");
                response.put("message", "Login successful");
                response.put("token", "fake-token-for-demo"); // 在实际项目中，这里应返回JWT
            } else {
                response.put("status", "error");
                response.put("message", "用户名或密码错误");
            }
        } catch (Exception e) {
            response.put("status", "error");
            response.put("message", e.getMessage());
        }

        return response;
    }

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody Map<String, String> userData) {
        String username = userData.get("username");
        String password = userData.get("password");
        String email = userData.get("email");

        Map<String, Object> response = new HashMap<>();

        try {
            User user = authService.register(username, password, email);
            response.put("status", "success");
            response.put("message", "Registration successful");
            response.put("user", user.getUsername());
        } catch (Exception e) {
            response.put("status", "error");
            response.put("message", e.getMessage());
        }

        return response;
    }
}